<template>
  <el-form
    ref="formRef"
    v-loading="formLoading"
    :model="formData"
    :rules="formRules"
    label-width="120px"
  >
    <el-row>
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item label="来源" prop="userSource">
          <el-select v-model="formData.userSource" placeholder="请选择">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SOURCE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item label="工号" prop="jobNumber">
          <el-input v-model="formData.jobNumber" />
        </el-form-item>
      </el-col>
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item label="岗位类型" prop="postType">
          <el-select v-model="formData.postType" multiple clearable placeholder="请选择">
            <el-option :label="'总部'" :value="3" />
            <el-option :label="'门店'" :value="4" />
            <el-option :label="'商城'" :value="5" />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item label="工作状态" prop="userStatus">
          <el-select v-model="formData.userStatus" placeholder="请选择" @change="userStatusChange">
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.EMPLOYEE_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item label="归属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            :disabled="!formData.postType.includes(3)"
            :data="deptList"
            :props="defaultProps"
            check-strictly
            node-key="id"
            placeholder="请选择归属部门"
          />
        </el-form-item>
      </el-col>
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item label="总部岗位" prop="postIds">
          <el-select
            v-model="formData.postIds"
            multiple
            placeholder="请选择"
            :disabled="!formData.postType.includes(3)"
          >
            <el-option
              v-for="item in postList"
              :key="item.id"
              :label="item.name"
              :value="item.id!"
            />
          </el-select>
        </el-form-item>
      </el-col>

      <!-- <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item v-if="formData.id === undefined" label="密码" prop="password">
          <el-input
            v-model="formData.password"
            placeholder="请输入密码"
            show-password
            autocomplete="new-password"
            type="password"
          />
        </el-form-item>
      </el-col> -->
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item label="入职日期" prop="entryDate">
          <el-date-picker
            class="!w-full"
            v-model="formData.entryDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="入职日期"
          />
        </el-form-item>
      </el-col>
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
        <el-form-item label="转正日期" prop="officialDate">
          <el-date-picker
            class="!w-full"
            v-model="formData.officialDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="转正日期"
          />
        </el-form-item>
      </el-col>
      <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8" v-if="formData.userStatus == 5">
        <el-form-item label="离职日期" prop="dimissionDate">
          <el-date-picker
            class="!w-full"
            v-model="formData.dimissionDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="离职日期"
          />
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <template v-if="formData.tenantRelevancys.length == 0">
          <el-row>
            <el-col :span="12">
              <el-form-item label="关联商户">
                <el-button @click="addTenantRelevancys">关联商户</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <template v-else>
          <el-row v-for="(item, index) in formData.tenantRelevancys" :key="index">
            <el-col :span="8">
              <el-form-item label="关联商户">
                <el-select v-model="item.tenantId" placeholder="请选择关联商户">
                  <template #label="{ label, value }">
                    {{ label }}
                    <DictTag
                      class="ml-10px"
                      :type="DICT_TYPE.TENANT_IDENTITY"
                      :value="getTenantType(value)!"
                    />
                  </template>
                  <el-option
                    v-for="tenant in tenantList"
                    @click="handleTenantClick(tenant, item)"
                    :key="tenant.id"
                    :label="tenant.name"
                    :value="tenant.id!"
                    :disabled="TenantRelevancysTenantIds.includes(tenant.id)"
                    >{{ tenant.name }}
                    <DictTag
                      class="ml-10px"
                      :type="DICT_TYPE.TENANT_IDENTITY"
                      :value="tenant.tenantType!"
                  /></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item :label="`岗位`">
                <template #label
                  ><DictText
                    class="ml-10px"
                    :type="DICT_TYPE.TENANT_IDENTITY"
                    :value="getTenantType(item.tenantId)!"
                  />岗位
                </template>
                <!-- 如果选择了门店岗 或者商城岗 并且租户类型为门店岗位或者商城岗位时 才可以选择岗位 -->
                <div class="flex w-full">
                  <el-select
                    v-model="item.postIds"
                    multiple
                    collapse-tags
                    :disabled="
                      item.tenantId == '' ||
                      (!formData.postType.includes(4) && item.tenantType == 4) ||
                      (!formData.postType.includes(5) && item.tenantType == 5)
                    "
                    collapse-tags-tooltip
                    placeholder="请选择岗位"
                  >
                    <el-option
                      v-for="post in getPostMenuList(item.tenantId)"
                      :key="post.id"
                      :label="post.name"
                      :value="post.id!"
                      >{{ post.name }}</el-option
                    >
                  </el-select>
                  <el-checkbox border label="销售岗位" v-model="item.salesEnable" />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="关联角色">
                <div class="flex items-center w-full">
                  <el-select
                    v-model="item.roleIds"
                    multiple
                    collapse-tags
                    :disabled="item.tenantId == ''"
                    collapse-tags-tooltip
                    placeholder="请选择角色"
                  >
                    <el-option
                      v-for="role in getRoleMenuList(item.tenantId)"
                      :key="role.id"
                      :label="role.name"
                      :value="role.id!"
                      >{{ role.name }}</el-option
                    >
                  </el-select>
                  <el-button
                    class="ml-5px!"
                    type="primary"
                    link
                    @click.prevent="removeTenantRelevancys(item)"
                  >
                    <Icon icon="ep:minus" :size="20" />
                  </el-button>
                  <el-button
                    class="ml-5px!"
                    type="primary"
                    link
                    @click.prevent="addTenantRelevancys"
                  >
                    <Icon icon="ep:plus" :size="20" />
                  </el-button>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-col>
    </el-row>
  </el-form>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/system/post'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'
import * as TenantApi from '@/api/system/tenant'

import { FormRules } from 'element-plus'
import DictTag from '@/components/DictTag/src/DictTag.vue'
import { copyValueToTarget } from '@/utils'
import { propTypes } from '@/utils/propTypes'

defineOptions({ name: 'SystemPostForm' })
const props = defineProps({
  propFormData: {
    type: Object as PropType<UserApi.UserVO>,
    default: () => {}
  },
  activeName: propTypes.string.def('post')
})

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const message = useMessage() // 消息弹窗

const formData = reactive({
  userSource: '',
  deptId: '',
  id: undefined,
  postType: [] as any,
  // password: '',
  entryDate: '', //入职日期
  officialDate: '', //转正日期
  dimissionDate: '', //离职日期
  jobNumber: '',
  dateLeft: '',
  postIds: [],
  userStatus: undefined,
  tenantRelevancys: [] as any
})
const formRules = reactive<FormRules>({
  // nickname: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  // password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
  // deptId: [{ required: true, message: '归属部门不能为空', trigger: 'change' }],
  // postIds: [{ required: true, message: '岗位不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref([] as PostApi.PostVO[]) // 岗位列表
const tenantList = ref([] as TenantApi.ChildTenantWithPostListVO[]) //租户列表
const TenantRelevancysTenantIds = computed(() => {
  let ids = [] as any
  formData.tenantRelevancys.forEach((element) => {
    ids.push(element.tenantId)
  })
  return ids
})
/** 添加关联门店*/
const addTenantRelevancys = () => {
  formData.tenantRelevancys.push({
    tenantId: '',
    tenantType: '',
    deptId: '',
    salesEnable: false,
    postIds: [],
    roleIds: []
  })
}
/** 删除关联门店*/
const removeTenantRelevancys = (item) => {
  const index = formData.tenantRelevancys.indexOf(item)
  if (index !== -1) {
    formData.tenantRelevancys.splice(index, 1)
  }
}
/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
  },
  {
    immediate: true
  }
)
/**
 * 员工状态改变
 */

const userStatusChange = () => {
  if (formData.userStatus == 5) {
    emit('updateStatus', 1)
  }
}
/** 表单校验 */
const emit = defineEmits(['update:activeName', 'updateStatus'])
const validate = async () => {
  if (!formRef) return
  try {
    await unref(formRef)?.validate()
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【岗位信息】不完善，请填写相关信息')
    emit('update:activeName', 'post')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
onMounted(async () => {
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getSimpleDeptList())
  // 加载当前租户岗位列表
  let currentTenantData = await TenantApi.getCurrentTenantWithPost()
  postList.value = currentTenantData.posts
  // 加载当前租户创建的租户列表(带岗位列表)
  tenantList.value = await TenantApi.getChildTenantWithPostList()
})

const getTenantType = (id) => {
  if (!id) {
    return ''
  }
  let currentTenant = tenantList.value.filter((ele) => {
    return ele.id == id
  })
  let tenantType = currentTenant[0]?.tenantType
  return tenantType
  // 获取选择对应商户的 类型
}
const getPostMenuList = (id) => {
  console.log('post')
  // 获取对应租户的岗位列表
  if (!id) {
    return []
  }
  let currentTenant = tenantList.value.filter((ele) => {
    return ele.id == id
  })
  let postList = currentTenant[0]?.posts
  return postList
}
const getRoleMenuList = (id) => {
  // 获取对应租户的岗位列表
  if (!id) {
    return []
  }
  let currentTenant = tenantList.value.filter((ele) => {
    return ele.id == id
  })
  let roleList = currentTenant[0]?.roles
  console.log(roleList)
  return roleList
}
const handleTenantClick = async (tenant, item) => {
  item.postIds = []
  item.roleIds = []
  item.deptId = tenant.deptId
  item.tenantType = tenant.tenantType
}
</script>
